package com.piece.core.framework.util.file;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import java.io.*;

/**
 * 文本文件编码探测工具类
 */
public class FileCharsetDetector {

    /**
     * 传入一个文件(File)对象，检查文件编码
     *
     * @param file File对象实例
     * @return 文件编码，若无，则返回null
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static Observer guessFileEncoding(File file) throws FileNotFoundException, IOException {
        return guessFileEncoding(new BufferedInputStream(new FileInputStream(file)), new nsDetector());
    }

    /**
     * 获取文件的编码
     *
     * @param file         File对象实例
     * @param languageHint 语言提示区域代码 @see #nsPSMDetector ,取值如下：
     *                     1 : Japanese
     *                     2 : Chinese
     *                     3 : Simplified Chinese
     *                     4 : Traditional Chinese
     *                     5 : Korean
     *                     6 : Dont know(default)
     * @return 文件编码
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static Observer guessFileEncoding(File file, int languageHint) throws FileNotFoundException, IOException {
        return guessFileEncoding(new BufferedInputStream(new FileInputStream(file)), new nsDetector(languageHint));
    }

    /**
     * 传入一个文件(File)对象，检查文件编码
     *
     * @param inputStream 文件流
     * @return 文件编码，若无，则返回null
     * @throws IOException
     */
    public static Observer guessFileEncoding(InputStream inputStream) throws IOException {
        return guessFileEncoding(new BufferedInputStream(inputStream), new nsDetector());
    }

    /**
     * 获取文件的编码
     */
    private static Observer guessFileEncoding(BufferedInputStream imp, nsDetector det) throws IOException {
        Observer observer = new Observer();
        det.Init(observer);

        byte[] buf = new byte[1024];
        int len;
        boolean done = false;
        boolean isAscii = false;

        while ((len = imp.read(buf, 0, buf.length)) != -1) {
            // Check if the stream is only ascii.
            isAscii = det.isAscii(buf, len);
            if (isAscii) {
                break;
            }
            // DoIt if non-ascii and not done yet.
            done = det.DoIt(buf, len, false);
            if (done) {
                break;
            }
        }
        imp.close();
        det.DataEnd();

        if (isAscii) {
            observer.encoding = "ASCII";
            observer.found = true;
        }

        if (!observer.isFound()) {
            String[] prob = det.getProbableCharsets();
            if (prob.length > 0) {
                // 在没有发现情况下,取第一个可能的编码
                observer.encoding = prob[0];
            } else {
                observer.encoding = null;
            }
        }
        return observer;
    }

    /**
     * 文件字符编码观察者
     */
    public static class Observer implements nsICharsetDetectionObserver {
        /**
         * @Fields encoding : 字符编码
         */
        private String encoding = null;
        /**
         * @Fields found : 是否找到字符集
         */
        private boolean found = false;

        @Override
        public void Notify(String charset) {
            this.encoding = charset;
            this.found = true;
        }

        public String getEncoding() {
            return encoding;
        }

        public boolean isFound() {
            return found;
        }

        @Override
        public String toString() {
            return "Observer [encoding=" + encoding + ", found=" + found + "]";
        }
    }
}
